package com.leyou.user.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final static String KEY_PREFIX = "user:verify:code:";    //存入redis中的前缀

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 数据校验
     * @param data  检验数据
     * @param type  校验数据类型: 1.用户名 2.手机
     * @return
     */
    public Boolean checkData(String data, Integer type) {
        User user = new User();
        switch (type){
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        return userMapper.selectCount(user) == 0;
    }

    /**
     * 发送短信验证码
     * @param phone 手机号
     */
    public void sendCode(String phone) {
        //服务端接收并验证手机号
        if (!RegexUtils.isPhone(phone)){
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }
        //生成随机验证码(并存储到Redis中)
        String code = RandomStringUtils.randomNumeric(6);
        //存入redis中: 有效期为 5 min
        String key = KEY_PREFIX + phone;
        stringRedisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);

        Map<String, String> msg = new HashMap<>();
        msg.put("phone",phone);
        msg.put("code",code);

        log.info("【用户微服务】获取短信验证码: {}",msg);

        amqpTemplate.convertAndSend( SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
    }

    /**
     * 用户注册
     * @param user  封装数据实体类
     * @param code  验证码
     */
    @Transactional  //需要事务
    public void register(User user, String code) {
        //1.校验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (!StringUtils.equals(code,cacheCode)){
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }

        //2.对密码加密
        String password = user.getPassword();
        user.setPassword(passwordEncoder.encode(password));

        //3.存入数据库
        int count = userMapper.insertSelective(user);
        if (count != 1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    /**
     * 根据用户名和密码查询用户信息
     * @param username  用户名
     * @param password  密码
     * @return  用户信息
     */
    public UserDTO queryUserByUsernameAndPassword(String username, String password) {
        //1.根据用户名查询
        User u = new User();
        u.setUsername(username);
        User user = userMapper.selectOne(u);
        //2.判断是否存在
        if (user == null){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //3.校验密码
        if (!passwordEncoder.matches(password,user.getPassword())){
            //密码错误
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        return BeanHelper.copyProperties(user,UserDTO.class);
    }
}
